package com.c.ctgproject.ui.collect

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.adapter.guang.AddPartAdapter
import com.c.ctgproject.adapter.guang.DictionarySelectAdapter
import com.c.ctgproject.adapter.guang.MaterialChildSelectAdapter
import com.c.ctgproject.adapter.guang.PartSelectAdapter
import com.c.ctgproject.base.BaseActivityV2
import com.c.ctgproject.databinding.ActivityDictionaryMenuBinding
import com.c.ctgproject.entity.guang.*
import com.c.ctgproject.enum.DictionaryMenuEnum
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserverHandlerLoading
import com.c.ctgproject.utils.*
import com.c.ctgproject.wiget.common.ListSelectDialog
import kotlinx.android.synthetic.main.activity_main.view.*

/**
 *作者:LiBW
 *创建日期: 2021/9/25
 *描述: 字典列表
 */
class DictionaryMenuActivity : BaseActivityV2(), DictionarySelectAdapter.PartSelectAdapterListener, MaterialChildSelectAdapter.MaterialChildSelectAdapter {
    private val mBinding by lazy { ActivityDictionaryMenuBinding.inflate(layoutInflater) }
    override fun getLayout() = mBinding.root

    //之前选中的数据
    private val oldList by lazy { intent.getStringArrayListExtra(MyConstants.DATA) }

    //单选模式
    private val mSingleModel by lazy { intent.getBooleanExtra(MyConstants.SINGLE_MODEL, false) }

    //是否可以手输
    private val mCanInput by lazy { intent.getBooleanExtra(MyConstants.CAN_INPUT, false) }

    //需要查询什么
    private val dictionaryCode by lazy { intent.getStringExtra(MyConstants.CODE) }
    private var mList = ArrayList<DictionaryChildBean>()
    private val mCopyList = ArrayList<DictionaryChildBean>()
    private val mAdapter by lazy { DictionarySelectAdapter(this, mList, this) }
    private var target = ""
    private val parentPosition by lazy { intent.getIntExtra(MyConstants.POSITION,-1)}
    //选择配件 配件字典跟其他不一样了 修改了
    private val partFrom: Int by lazy { intent.getIntExtra(MyConstants.PART_FROM, -1) }
    override fun event() {
        target = DictionaryMenuEnum.getPartName(dictionaryCode)
        when (dictionaryCode) {
            DictionaryMenuEnum.CHECK_USER.menuCode->mBinding.mTitleBar.setTitle("审批人员选择")
            DictionaryMenuEnum.BATTERY.menuCode -> mBinding.mTitleBar.setTitle("电池选择")
            DictionaryMenuEnum.PARTS.menuCode -> mBinding.mTitleBar.setTitle("配件选择")
            DictionaryMenuEnum.UNIT.menuCode -> mBinding.mTitleBar.setTitle("计量单位选择")
            DictionaryMenuEnum.CUSTOMER.menuCode -> mBinding.mTitleBar.setTitle("客户选择")
            DictionaryMenuEnum.SUPPLIER.menuCode -> mBinding.mTitleBar.setTitle("供应商选择")
        }
        mBinding.mInputLL.visibility = if (mCanInput) View.VISIBLE else View.GONE

        when (partFrom) {
            -1 -> {
                ApiMethods.apiSubscribe(ApiMethods.retrofit.getDictionaryMenu(dictionaryCode), MyObserverHandlerLoading(this,loading) {
                    MyLog.d("字典回调:$it")
                    val data = getGson().fromJson(it, DictionaryMenuEntity::class.java).data
                    data?.list?.let { beanList ->

                        val list = ArrayList<DictionaryChildBean>()
                        beanList.forEach { child ->
                            val b = DictionaryChildBean()
                            b.key = child.dictLabel.handlerNull()
                            b.value = child.dictValue.handlerNull()
                            list.add(b)
                        }


                        list.forEach { bean ->
                            if (bean.key in oldList && bean.key.handlerNull().isNotEmpty()) {
                                bean.isSelect = true
                            }
                        }
                        //只有一个数据的时候判断一下是否为手输的
                        if (oldList.size == 1 && oldList[0].isNotEmpty()) {
                            val name = oldList[0]
                            var isInput = true
                            list.forEach { bean ->
                                //找到相同的了就不是手输的了
                                if (name == bean.key) isInput = false
                            }
                            if (isInput) {
                                mBinding.mInputET.textSet(name)
                                mBinding.mCheckBox.isChecked = true
                            }
                        }
                        mList.addAll(list)
                        mCopyList.addAll(list)
                        MyLog.d("目标目标:${getGson().toJson(mList)}")
                        MyLog.d("目标目标2:${getGson().toJson(beanList)}")
                        mBinding.mRecyclerView.adapter = mAdapter
                        mBinding.mRecyclerView.layoutManager = LinearLayoutManager(this)
                    }
                })
            }
            3 -> {
                MyLog.d("进门了么")
                ApiMethods.apiSubscribe(ApiMethods.retrofit.materialChildList(), MyObserverHandlerLoading(this, loading) {
                    MyLog.d("物料列表回调:$it")
                    val data = getGson().fromJson(it, MaterialChildListEntity::class.java).data
                    data?.let { list ->
                        val l = ArrayList<DictionaryChildBean>()
                        list.forEach { bean ->
                            val b = DictionaryChildBean()
                            b.key = bean.materialName
                            b.value = bean.materialCode
                            l.add(b)
                        }


                        l.forEach { bean ->
                            if (bean.key in oldList && bean.key.handlerNull().isNotEmpty()) {
                                bean.isSelect = true
                            }
                        }
                        mList.addAll(l)
                        mCopyList.addAll(l)
                        mBinding.mRecyclerView.adapter = mAdapter
                        mBinding.mRecyclerView.layoutManager = LinearLayoutManager(this)


//                        val adapter = MaterialChildSelectAdapter(this, list, this)
//                        mBinding.mRecyclerView.adapter = adapter
//                        mBinding.mRecyclerView.layoutManager = LinearLayoutManager(this)
                    }
                })
            }
            1 -> {

                //散件
                ApiMethods.apiSubscribe(ApiMethods.retrofit.getDictionaryMenuV2(isBulkParts = 1), MyObserverHandlerLoading(this, loading) {
                    MyLog.d("散件回调:$it")
                    val data = getGson().fromJson(it, DictionaryPartMenuEntity::class.java).data
                    data?.let { list ->
                        list.forEach { bean ->
                            if (bean.key in oldList && bean.key.handlerNull().isNotEmpty()) {
                                bean.isSelect = true
                            }
                        }
                        //只有一个数据的时候判断一下是否为手输的
                        if (oldList.size == 1 && oldList[0].isNotEmpty()) {
                            val name = oldList[0]
                            var isInput = true
                            list.forEach { bean ->
                                //找到相同的了就不是手输的了
                                if (name == bean.key) isInput = false
                            }
                            if (isInput) {
                                mBinding.mInputET.textSet(name)
                                mBinding.mCheckBox.isChecked = true
                            }
                        }

                        mList.addAll(list)
                        mCopyList.addAll(list)
                        mBinding.mRecyclerView.adapter = mAdapter
                        mBinding.mRecyclerView.layoutManager = LinearLayoutManager(this)
                    }
                })
            }
            4 -> {
                //审批人
                ApiMethods.apiSubscribe(ApiMethods.urmRetrofit.getDepartmentUser(), MyObserverHandlerLoading(this, loading, zeroIsSuccess = true) {
                    MyLog.d("审批人回调:$it")
                    val data = getGson().fromJson(it, CheckUserAdminEntity::class.java).data
                    data?.let {list->
                        val l = ArrayList<DictionaryChildBean>()
                        list.forEach { bean ->
                            val b = DictionaryChildBean()
                            b.key = bean.realName.handlerNull()
                            b.value = bean.userId.handlerNull()
                            l.add(b)
                        }

                        l.forEach { bean ->
                            if (bean.key in oldList && bean.key.handlerNull().isNotEmpty()) {
                                bean.isSelect = true
                            }
                        }

                        mList.addAll(l)
                        mCopyList.addAll(l)
                        mBinding.mRecyclerView.adapter = mAdapter
                        mBinding.mRecyclerView.layoutManager = LinearLayoutManager(this)
                    }
                })
            }
        }
    }

    override fun click() {
        mBinding.mSearchET.handlerText {
            if (it.isEmpty()) {
                mList.clear()
                mList.addAll(mCopyList)
                mAdapter.notifyDataSetChanged()
                MyLog.d("呦呵来了1:${mList.size}")

            } else {
                mList.clear()
                mCopyList.forEach { search ->
                    if (it in search.key.handlerNull()) {
                        mList.add(search)
                    }
                }
                mAdapter.notifyDataSetChanged()
                MyLog.d("呦呵来了2:${mList.size}")

            }
        }

        mBinding.mCheckBox.setOnClickListener {
            //如果按钮呗选中并且是单选模式则清除列表中的选中状态
            if (mBinding.mCheckBox.isChecked && mSingleModel) {
                mList.forEachIndexed { index, listBean ->
                    if (listBean.isSelect) {
                        listBean.isSelect = false
                        mAdapter.notifyItemChanged(index)
                    }
                }
            }
        }


        mBinding.mConfirmBTN.setOnClickListener {
            //单选情况下 自定义输入框选中但是没有内容
            if (mSingleModel && mBinding.mCheckBox.isChecked && mBinding.mInputET.text.handlerNull().isEmpty()) {
                showToast("请输入自定义${target}内容后继续")
                return@setOnClickListener
            }
            val selectList = ArrayList<DictionaryChildBean>()
            mList.forEach {
                if (it.isSelect) selectList.add(it)
            }
            //没有选中的
            if (selectList.isEmpty() && !mBinding.mCheckBox.isChecked) {
                showToast("请选择${target}后继续")
                return@setOnClickListener
            }
            val intent = Intent()
            if (mSingleModel) {
                if (mBinding.mCheckBox.isChecked) {
                    intent.putExtra(MyConstants.NAME, mBinding.mInputET.text.handlerNull())
                } else {
                    intent.putExtra(MyConstants.NAME, selectList[0].key.handlerNull())
                    intent.putExtra(MyConstants.ABBREVIATION, selectList[0].value.handlerNull())
                }
            } else {
                val selects = ArrayList<String>()
                selectList.forEach {
                    selects.add(it.key.handlerNull())
                }
                intent.putStringArrayListExtra(MyConstants.DATA, selects)
            }
            intent.putExtra(MyConstants.POSITION,parentPosition)
            setResult(1000, intent)
            finish()
        }
    }

    override fun onItemSelect(position: Int, select: Boolean) {
        if (mSingleModel) {
            mList.forEach {
                it.isSelect = false
            }
            mList[position].isSelect = true
            mAdapter.notifyDataSetChanged()
            mBinding.mCheckBox.isChecked = false

        } else {
            mList[position].isSelect = select
            mAdapter.notifyItemChanged(position)
        }
    }

    //2以后为我自定义
    companion object {
        /**
         *
         * partFrom 1:散件 零件 2:初检 入库 3.选择物料 4.审批人
         * */
        fun jumpToDictionary(context: FragmentActivity, dictionaryCode: String, singeMode: Boolean, oldList: ArrayList<String>, canInput: Boolean = true, resultCode: Int = 1000, partFrom: Int? = null,parentPosition:Int?=null) {
            val intent = Intent(context, DictionaryMenuActivity::class.java)
            intent.putExtra(MyConstants.CODE, dictionaryCode)
            intent.putExtra(MyConstants.SINGLE_MODEL, singeMode)
            intent.putExtra(MyConstants.CAN_INPUT, canInput)
            intent.putExtra(MyConstants.PART_FROM, partFrom)
            intent.putExtra(MyConstants.POSITION,parentPosition)
            intent.putStringArrayListExtra(MyConstants.DATA, oldList)
            context.startActivityForResult(intent, resultCode)
        }
    }

    override fun onItemClick(position: Int) {

    }
}